var app = getApp();
var util = require('../../utils/util.js');

import {
  $stopWuxRefresher
} from '../../dist/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items:[],
    id:0,
    content:[],
    placeholder:"评论",
    parentId: '',
    inputValue:"",
    show:false,
    tab:true,
    host: wx.getStorageSync('host'),
    windowHeight:0,
    block:'none',
    over:'none',
    kong:false,
    ii:[],
    toUserId:0,
    name: wx.getStorageSync('allid')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var id = options.id;
    console.log(wx.getStorageSync('allid'))
    var that = this;
    var url = wx.getStorageSync('url');
    var authorization = wx.getStorageSync('authorization');
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
             
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况

              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)

              }
            }
          })
        } else {
          wx.reLaunch({
            url: '/pages/login/index',
          })
        }
      }
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight-90  + "px",
          name: wx.getStorageSync('allid')
        })
      }
    })
    that.setData({
      id: options.id,
      kong:true
    })
    wx.request({
      url: url + '/v1/article/%7Bid%7D',
      data: {
        id:id
      },
      method: "get",
      header: {
        'content-Type': 'application/json',
        'authorization': authorization
      },
      success: function (res) {
        var list = ""
        var list = res.data.data.mpArticleDetailResponse
        if (list == undefined) {
          that.setData({
            block: "block",
            over: "none"
          })
        } else {
          that.setData({
            block: "none",
            over: "block"
          })
        }
          list.image = list.image.split(",")
        
          if (list.type == 1) {
            list.ctype = '求助'
          } else if (list.type == 2) {
            list.ctype = '闲置'
          } else if (list.type == 3) {
            list.ctype = '兼职'
          } else if (list.type == 4) {
            list.ctype = '租房'
          } else if (list.type == 5) {
            list.ctype = '寻物'
          } else if (list.type == 6) {
            list.ctype = '招领'
          } else if (list.type == 7) {
            list.ctype = '投稿'
          } else if (list.type == 8) {
            list.ctype = '表白'
          }
        that.setData({
          items: list,
          kong:false
        })
       
      },
      fail: function (res) {
        
      },
    });
    wx.request({
      url: url + '/v1/article/%7Bid%7D/detail/comment',
      data: {
        id: id
      },
      method: "get",
      header: {
        'content-Type': 'application/json',
        'authorization': authorization
      },
      success: function (res) {
        var list = [];
        var long = [];
        list = res.data.data.mpComments
        for (var i = 0 ;i <list.length;i++){
          list[i].gmtCreated = list[i].gmtCreated.replace(new RegExp("-", "gm"), "/"),
          list[i].gmtCreated = (new Date(list[i].gmtCreated)).getTime(),
          list[i].gmtCreated = util.timeago(list[i].gmtCreated)
          long = list[i].mpArticleCommentReverts
          if (long !=''){
          for (var j = 0; j < long.length; j++) {
            list[i].mpArticleCommentReverts[j].gmtCreated = long[j].gmtCreated.replace(new RegExp("-", "gm"), "/"),
              list[i].mpArticleCommentReverts[j].gmtCreated = (new Date(long[j].gmtCreated)).getTime(),
              list[i].mpArticleCommentReverts[j].gmtCreated = util.timeago(long[j].gmtCreated)
          }
          }
        }
       that.setData({
         content: list,
       })
      },
      fail: function (res) {

      },
    });
  },
  jubao(e){
    wx.navigateTo({
      url: '/pages/feedback/index?id=' + this.data.id + "&name=" + e.currentTarget.dataset.os
    })
  },
  btnleft(){
    var that = this
    var id = that.data.id
    var url = wx.getStorageSync('url')
    var authorization = wx.getStorageSync('authorization')
    wx.request({
      url: url + '/v1/article/%7Bid%7D/collections',
      data: {
        id: id
      },
      method: "post",
      header: {
        'content-Type': 'application/json',
        'authorization': authorization
      },
      success: function (res) {
        wx.showToast({
          title: "收藏成功",
          icon: 'success',
          duration: 1000
        })
      },
      fail: function (res) {

      },
    });
  },
  onRefresh(e) {

    var that = this;
    var id = that.data.id
    var url = wx.getStorageSync('url')
    var authorization = wx.getStorageSync('authorization')
    setTimeout(() => {
      wx.request({
        url: url + '/v1/article/%7Bid%7D?',
        data: {
          id: id
        },
        method: "get",
        header: {
          'content-Type': 'application/json',
          'authorization': authorization,
          'openid': wx.getStorageSync('openid')
        },
        success: function (res) {
          var list = res.data.data.mpArticleDetailResponse
          if (list == undefined) {
            that.setData({
              over:"none",
              block: "block"
            })
          } else {
            that.setData({
              block: "none",
              over: "block"
            })
          }
          list.image = list.image.split(",")
            if (list.type == 1) {
              list.ctype = '求助'
            } else if (list.type == 2) {
              list.ctype = '闲置'
            } else if (list.type == 3) {
              list.ctype = '兼职'
            } else if (list.type == 4) {
              list.ctype = '租房'
            } else if (list.type == 5) {
              list.ctype = '寻物'
            } else if (list.type == 6) {
              list.ctype = '招领'
            } else if (list.type == 7) {
              list.ctype = '投稿'
            } else if (list.type == 8) {
              list.ctype = '表白'
            }
          
          that.setData({
            items: list
          })
  
        },
        fail: function (res) {

        },
      });
      wx.request({
        url: url + '/v1/article/%7Bid%7D/detail/comment',
        data: {
          id: id
        },
        method: "get",
        header: {
          'content-Type': 'application/json',
          'authorization': authorization,
          'openid': wx.getStorageSync('openid')
        },
        success: function (res) {
          that.setData({
            content: res.data.data.mpComments,

          })
        },
        fail: function (res) {

        },
      });


      $stopWuxRefresher()
    }, 2000)
  },
 submit(e) {

    var that = this
    var url = wx.getStorageSync('url')
    var value = that.data.inputValue
   var articleId = parseInt(that.data.id)
   if (that.data.placeholder == '回复:' && wx.getStorageSync('allid') != that.data.toUserId && value!=""){
     wx.request({
       url: url + '/v1/article/comment/revert',
       data: {
         articleId: articleId,
         content: value,
         toCommentId: that.data.parentId
        
       },
       method: "post",
       header: {
         'content-Type': 'application/json',
         'authorization': wx.getStorageSync('authorization'),
         'openid': wx.getStorageSync('openid')
       },
       success: function (res) {
         var list = {
           nickName: wx.getStorageSync('nickName'),
           content: that.data.inputValue,
           parentId: that.data.parentId,
           toNickName: that.data.nickname,
           gmtCreated:"刚刚"
         }
         var cc = that.data.content
     
        for(var i =0;i<cc.length;i++){
          if (cc[i].id == that.data.parentId){
            cc[i].mpArticleCommentReverts.push(list)
          }
        }
        
         that.setData({
           inputValue: '',
           content: cc,
           placeholder: '评论:',
           show: false,
           tab: true
         })
       },
       fail: function (res) {
         // console.log(res)
       },
     });
   }else if(value!=""){
   
     wx.request({
       url: url + '/v1/article/comment',
       data: {
         articleId: articleId,
         content: value
       },
       method: "post",
       header: {
         'content-Type': 'application/json',
         'authorization': wx.getStorageSync('authorization'),
         'openid': wx.getStorageSync('openid')
       },
       success: function (res) {
         var list = {
           nickName: wx.getStorageSync('nickName'),
           content: that.data.inputValue,
           parentId: 0,
           headPortrait: wx.getStorageSync('headPortrait')
         }
         var cc = that.data.content
         
         console.log(that.data.items.commentNumber) 
         var item =  that.data.items;
         item.commentNumber = that.data.items.commentNumber+1
         cc.push(list)
        
         that.setData({
           items: item,
           inputValue: '',
           content:cc,
           show:false,
           tab:true
         })
       },
       fail: function (res) {
         // console.log(res)
       },
     });
   }else{
     that.setData({
       value:"评论不能为空"
     })
   }
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value, //将input至与data中的inputValue绑定
    })
  },
  foo: function () {
    if (this.data.inputValue) {
      //Do Something
    } else {
      //Catch Error
    }
    // this.setData({
    //   inputValue: '' //将data的inputValue清空
    // });
    return;
  },
  reply: function (e) {

    this.setData({
      placeholder: '回复:' + e.currentTarget.dataset.nickname,
      parentId: e.currentTarget.dataset.ids,
      toUserId: e.currentTarget.dataset.uids,
      nickname: e.currentTarget.dataset.nickname,
      show: true,
      tab: false,
    })
  },
  
  show(e){
    this.setData({
      show:true,
      tab:false
    })
  },
  big(e) {
    var that = this
    var host = that.data.host
    var current = e.currentTarget.dataset.img;
    var ix = e.currentTarget.dataset.ix;
    for (var i = 0; i < current.length; i++) {
      current[i] = host + current[i]
    }
    that.setData({
      ii: current
    })
    wx.previewImage({
      current: that.data.ii[ix],
      urls: that.data.ii// 需要预览的图片http链接列表
    })

  },
  onShareAppMessage: (res) => {
    var that = this
    var id = res.id
    return {
      title: '蚂蚁大学',
      imageUrl: "../../astatic/zhanshi.png",
      path: '/pages/index/Details?id=' + that.data.id ,
      success: function (shareTickets) {
        console.info(shareTickets + '成功');
        // 转发成功
      },
      fail: function (res) {
        console.log(res + '失败');
        // 转发失败
      },

    }
  },
  del(e){
    console.log(e)
    var that = this;
    let url = wx.getStorageSync('url');
    wx.showModal({
      title: '提示',
      content: '确定删除此帖子',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: url + "/v1/user/article/%7Bid%7D?id=" + e.currentTarget.dataset.ids,
            data: {
            },
            method: "DELETE",
            header: {
              'content-type': 'json',
              'authorization': wx.getStorageSync('authorization')
            },
            success: function (res) {
              that.setData({
                block: 'block',
                over: 'none'
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
   
  },
  onPullDownRefresh() {
    var that = this
    var url = wx.getStorageSync('url')
    var authorization = wx.getStorageSync('authorization')
    wx.request({
      url: url + '/v1/article/%7Bid%7D',
      data: {
        id: that.data.id
      },
      method: "get",
      header: {
        'content-Type': 'application/json',
        'authorization': authorization
      },
      success: function (res) {
        var list = ""
        var list = res.data.data.mpArticleDetailResponse

        if (list == undefined) {
          that.setData({
            block: "block",
            over: "none"
          })
        } else {
          that.setData({
            block: "none",
            over: "block"
          })
        }
        list.image = list.image.split(",")

        if (list.type == 1) {
          list.ctype = '求助'
        } else if (list.type == 2) {
          list.ctype = '闲置'
        } else if (list.type == 3) {
          list.ctype = '兼职'
        } else if (list.type == 4) {
          list.ctype = '租房'
        } else if (list.type == 5) {
          list.ctype = '寻物'
        } else if (list.type == 6) {
          list.ctype = '招领'
        } else if (list.type == 7) {
          list.ctype = '投稿'
        } else if (list.type == 8) {
          list.ctype = '表白'
        }


        that.setData({
          items: list,
          kong: false
        })

      },
      fail: function (res) {

      },
    });
    wx.request({
      url: url + '/v1/article/%7Bid%7D/detail/comment',
      data: {
        id: that.data.id
      },
      method: "get",
      header: {
        'content-Type': 'application/json',
        'authorization': authorization
      },
      success: function (res) {
        var list = [];
        var long = [];
        list = res.data.data.mpComments
        for (var i = 0; i < list.length; i++) {
          list[i].gmtCreated = list[i].gmtCreated.replace(new RegExp("-", "gm"), "/"),
            list[i].gmtCreated = (new Date(list[i].gmtCreated)).getTime(),
            list[i].gmtCreated = util.timeago(list[i].gmtCreated)
          long = list[i].mpArticleCommentReverts
          if (long != '') {
            for (var j = 0; j < long.length; j++) {
              list[i].mpArticleCommentReverts[j].gmtCreated = long[j].gmtCreated.replace(new RegExp("-", "gm"), "/"),
                list[i].mpArticleCommentReverts[j].gmtCreated = (new Date(long[j].gmtCreated)).getTime(),
                list[i].mpArticleCommentReverts[j].gmtCreated = util.timeago(long[j].gmtCreated)
            }
          }
        }
        that.setData({
          content: list,
        })
      },
      fail: function (res) {

      },
    });
    wx.stopPullDownRefresh()

  },
})